using System;
using System.IO;
using System.Drawing;
using System.Reflection;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

using Weazel.Toad.Application;
using Weazel.Toad.Application.Items;
using Weazel.Toad.Application.Actions;

namespace Weazel.Toad.Application.Controls.SimulationToolStrip
{
  public class SimulationToolStrip 
    : ToadToolStrip
  {
    private ToolStripLabel label;
    private ToolStripTextBox cyclesTextBox;
    private ToolStripButton runSimulationButton;
    private ToolStripButton stopSimulationButton;

    private int cyclesToRun;
    public int CyclesToRun
    {
      get
      {
        validateCycleCount();
        return cyclesToRun;
      }
    }

    public SimulationToolStrip()
    {
      // load images
      Image runImage = GraphicsLoader.LoadImage(GetType(), "run.png");
      Image stopImage = GraphicsLoader.LoadImage(GetType(), "stop.png");

      this.label = new ToolStripLabel("Simulation:");
      
      this.cyclesTextBox = new ToolStripTextBox();
      this.cyclesTextBox.ToolTipText = "Cycles to simulate";
      this.cyclesTextBox.Width = 100;
      this.cyclesTextBox.Text = "10"; 

      this.runSimulationButton = new ToolStripButton(runImage);
      this.runSimulationButton.ToolTipText = "Simulate the current Gezel design";

      this.stopSimulationButton = new ToolStripButton(stopImage);
      this.stopSimulationButton.ToolTipText = "Stop simulation";

      Items.AddRange(
        new ToolStripItem[] {
          this.label,
          this.cyclesTextBox,
          this.runSimulationButton,
          this.stopSimulationButton
        }
      );      
    }

    public override void BindActions()
    {
      // simulation run/stop items
      ActionBase.Actions[typeof(SimulateGezelModelAction)].BindToolStripItem(runSimulationButton);
      ActionBase.Actions[typeof(EndSimulationAction)].BindToolStripItem(stopSimulationButton);
    }

    private void validateCycleCount()
    {
      if (Application.Instance.SelectedItem is GezelTextFile)
      {
        GezelTextFile file = Application.Instance.SelectedItem as GezelTextFile;

        try
        {
          int cyclesRead = int.Parse(cyclesTextBox.Text);

          if (cyclesRead > 0)
            cyclesToRun = cyclesRead;
          else
            cyclesTextBox.Text = cyclesToRun.ToString();
        }
        catch (Exception)
        {
          cyclesTextBox.Text = cyclesToRun.ToString();
        }
      }
    }
  }
}
